<template>
  <common-list>
    <common-table
      slot="content"
      v-loading="loading"
      :data="templateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="模板编码"
        align="left"
        prop="code"
        show-overflow-tooltip
      />
      <el-table-column
        label="模板名称"
        align="left"
        prop="name"
        show-overflow-tooltip
      />
      <el-table-column
        label="模板主题"
        align="left"
        prop="subject"
        show-overflow-tooltip
      />
      <el-table-column label="操作" align="left" width="90px">
        <template slot-scope="scope">
          <el-button type="text" @click="getTemplate(scope.row, 2)"
            >详情
          </el-button>
          <el-button type="text" @click="handleUpdate(scope.row)"
            >编辑
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      :button-loading="isPersistenceLoading"
      @cancel="cancel"
      @submit="submitForm"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="18">
          <el-col :span="24">
            <el-form-item label="模板编码" prop="code">
              <common-input
                disabled
                v-model="form.code"
                placeholder="请输入模板编码"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板名称" prop="name">
              <common-input
                v-model="form.name"
                placeholder="请输入模板名称"
                :maxlength="32"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板主题" prop="subject">
              <common-input
                v-model="form.subject"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模板内容" prop="content">
              <!--          <common-input
                          v-model="form.content"
                          type="textarea"
                          :rows="6"
                          placeholder="请输入"
                        />-->
              <div style="width: 100%; height: 120px">
                <code-editor
                  key="message-editor"
                  v-model="form.content"
                  :variable="variable"
                ></code-editor>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <common-input
                v-model="form.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
    <common-info-dialog
      :visible.sync="detailsOpen"
      @cancel="cancel"
      :title="detailsTitle"
      :infoLoading="infoLoading"
    >
      <common-info-table>
        <common-info-table-cell label="模板编码"
          >{{ form.code }}
        </common-info-table-cell>
        <common-info-table-cell label="模板名称"
          >{{ form.name }}
        </common-info-table-cell>
        <common-info-table-cell label="模板主题"
          >{{ form.subject }}
        </common-info-table-cell>
        <common-info-table-cell label="模板内容">
          <span v-html="form.content"></span>
        </common-info-table-cell>
        <common-info-table-cell label="备注"
          >{{ form.remark }}
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>
  </common-list>
</template>

<script>
import {
  listTemplate,
  getTemplate,
  updateTemplate,
} from "@/api/system/emailtemplate";
import CodeEditor from "@/components/CodeEditor";
import BaseList from "@/mixins/BaseList";
import { getAlarmParam } from "@/api/system";

export default {
  name: "Template",
  mixins: [BaseList],
  components: {
    CodeEditor,
  },
  data() {
    const checkContent = (rule, value, callback) => {
      let num = 0,
        reg = new RegExp("<p>(&nbsp;|&nbsp;\\s+)+<\\/p>|<p>(<br>)+<\\/p>", "g"),
        regs = new RegExp("<p><\\/p>", "g");
      while (num < value.length && value != "") {
        num++;
        value = value.replace(/\s+/g, "");
        let k = value.match(reg);
        let d = value.match(regs);
        if (k) {
          value = value.replace(k[0], "");
        }
        if (d) {
          value = value.replace(d[0], "");
        }
      }
      if (value === "") {
        callback(new Error("请输入模板内容"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailsOpen: false,
      detailsTitle: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        id: "",
        code: "",
        name: "",
        subject: "",
        content: "",
        remark: "",
        createUserCode: "",
        createTime: "",
      },
      // 表单校验
      rules: {
        code: [{ required: true, message: "请输入模板编码", trigger: "blur" }],
        name: [{ required: true, message: "请输入模板名称", trigger: "blur" }],
        subject: [
          { required: true, message: "请输入模板主题", trigger: "blur" },
        ],
        content: [{ required: true, validator: checkContent, trigger: "blur" }],
      },
      variable: [],
      infoLoading: false,
      isPersistenceLoading: false,
    };
  },
  created() {
    this.getList();
    this.getAlarmParam();
  },
  methods: {
    getAlarmParam() {
      getAlarmParam().then((res) => {
        if (res?.code === 200) {
          this.variable = res.data.reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.id,
            });
            return r;
          }, []);
        } else {
          this.handleListTips(res);
        }
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams)
        .then((res) => {
          if (res && (res.code === 200 || res.rescode === 200)) {
            this.templateList = res.data.dataList;
            this.total = res.data.totalCount;
          } else {
            this.templateList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.detailsOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.emailTemplateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTemplate(row, 1);
    },
    getTemplate(row, n) {
      const id = row.id || this.ids;
      if (n === 1) {
        this.open = true;
        this.title = "编辑邮件内容模板";
      } else {
        this.detailsOpen = true;
        this.detailsTitle = "邮件内容模板详情";
      }
      this.getTemplateById(id);
    },

    getTemplateById(id) {
      this.infoLoading = true;
      getTemplate({ id }).then((response) => {
        if (response && (response.code === 200 || response.rescode === 200)) {
          this.form = response.data.dataList[0];
          this.infoLoading = false;
        } else {
          this.$GlobalErrorConfirm("获取信息失败", res.msg, "重新加载").then(
            () => {
              this.getTemplateById(id);
            }
          );
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            if (!this.isPersistenceLoading) {
              this.isPersistenceLoading = true;

              updateTemplate(
                Object.assign({}, this.form, { createTime: undefined })
              )
                .then((response) => {
                  if (
                    response &&
                    (response.code === 200 || response.rescode === 200)
                  ) {
                    this.$GlobalSuccessMessage("编辑成功");
                    this.open = false;
                    this.getList();
                  } else {
                    this.$GlobalErrorConfirm("编辑失败", response.msg);
                  }
                })
                .finally(() => {
                  this.isPersistenceLoading = false;
                });
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="scss">
.addOrEditClass {
  max-height: 66%;
  overflow-y: auto;
}
</style>
